package cn.afei.cloud.utils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具类
 */
public class Util {

    public static String getCertPath(HttpServletRequest request) {
        String basePath = request.getSession().getServletContext().getRealPath("/");
        StringBuffer uploadBasePath = new StringBuffer();
//		logger.info("服务器路径:" + basePath);
        basePath += "WEB-INF" + File.separator + "classes" + File.separator + "cert" + File.separator + "apiclient_cert.p12";
        return uploadBasePath.append(basePath).toString();
    }

    /**
     * @param ips
     * @return
     * @throws IOException
     */
    public static String inputStream2String(InputStream ips) throws IOException {

        BufferedReader in = new BufferedReader(new InputStreamReader(ips));

        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null) {
            buffer.append(new String(line.getBytes(), "utf-8"));
        }
        return buffer.toString();
    }

    /**
     * 通过反射的方式遍历对象的属性和属性值，方便调试
     *
     * @param o 要遍历的对象
     * @throws Exception
     */
    public static void reflect(Object o) throws Exception {
        Class<? extends Object> cls = o.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            f.setAccessible(true);
            Util.log(f.getName() + " -> " + f.get(o));
        }
    }

    public static byte[] readInput(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
        return out.toByteArray();
    }

    public static String inputStreamToString(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }


    public static InputStream getStringStream(String sInputString) throws UnsupportedEncodingException {
        ByteArrayInputStream tInputStringStream = null;
        if (sInputString != null && !sInputString.trim().equals("")) {
            tInputStringStream = new ByteArrayInputStream(sInputString.getBytes("UTF-8"));
        }
        return tInputStringStream;
    }


    public static String getStringFromMap(Map<String, Object> map, String key, String defaultValue) {
        if (key == "" || key == null) {
            return defaultValue;
        }
        String result = (String) map.get(key);
        if (result == null) {
            return defaultValue;
        } else {
            return result;
        }
    }

    public static int getIntFromMap(Map<String, Object> map, String key) {
        if (key == "" || key == null) {
            return 0;
        }
        if (map.get(key) == null) {
            return 0;
        }
        return Integer.parseInt((String) map.get(key));
    }

    /**
     * 打log接口
     *
     * @param log 要打印的log字符串
     * @return 返回log
     */
    public static String log(Object log) {
//        logger.info(log.toString());
        //System.out.println(log);
        return log.toString();
    }

    /**
     * 读取本地的xml数据，一般用来自测用
     *
     * @param localPath 本地xml文件路径
     * @return 读到的xml字符串
     */
    public static String getLocalXMLString(String localPath) throws IOException {
        return Util.inputStreamToString(Util.class.getResourceAsStream(localPath));
    }

    /**
     * @Function: 生成验证码
     * @author: zhenzhuobin
     */
    public static String getMsgCode() {
        int n = 4;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }

    /**
     * 判断当前操作系统是否为windows
     *
     * @return windwos操作系统为true，否则false
     */
    public final static boolean isWinOs() {
        return System.getProperties().getProperty("os.name").toLowerCase().startsWith("win");
    }

    /**
     * 判断当前请求是否来自IOS
     *
     * @return 如果是 IOS则为true，否则false
     */
    public final static boolean isIOS(HttpServletRequest request) {
        if (request == null || StringUtils.isBlank(request.getHeader("User-Agent"))) {
            return false;
        }
        String ua = request.getHeader("User-Agent").toLowerCase();
        return (ua.contains("iphone;") || ua.contains("iphone os") || ua.contains("mac os") || ua.contains("ipad;") || ua.contains("alsomeappios"));
    }

    /**
     * 判断当前请求是否来自Android
     *
     * @return 如果是 Android则为true，否则false
     */
    public final static boolean isAndroid(HttpServletRequest request) {
        if (request == null || StringUtils.isBlank(request.getHeader("User-Agent"))) {
            return false;
        }
        String ua = request.getHeader("User-Agent").toLowerCase();
        return (ua.contains("linux;") || ua.contains("android") || ua.contains("alsomeappandroid"));
    }

    /**
     * 判断当前请求是否来自微信打开
     *
     * @return 如果是 微信  则为true，否则false
     */
    public final static boolean isWeixinOpen(HttpServletRequest request) {
        if (request == null || StringUtils.isBlank(request.getHeader("User-Agent"))) {
            return false;
        }
        String ua = request.getHeader("User-Agent").toLowerCase();
        return ua.contains("micromessenger");
    }

    /**
     * 判断当前请求是否来自PC浏览器
     *
     * @return 如果是 PC浏览器 则为true，否则false
     */
    public final static boolean isPC(HttpServletRequest request) {
        return !isMobile(request);
    }

    /**
     * 判断当前请求是否来自手机端
     *
     * @return 如果是 手机端  则为true，否则false
     */
    public final static boolean isMobile(HttpServletRequest request) {
        if (request == null || StringUtils.isBlank(request.getHeader("User-Agent"))) {
            return false;
        }
        String ua = request.getHeader("User-Agent").toLowerCase();
        String mobile = ".*mobile.*";
        return (ua.matches(mobile) || isAndroid(request) || isIOS(request));
    }


    public final static int getTerminal(HttpServletRequest request) {
        int terminal = 0;
        if (isMobile(request)) {
            terminal = 0;
        }

        if (isAndroid(request)) {
            terminal = 1;
        }

        if (isIOS(request)) {
            terminal = 2;
        }
        return terminal;
    }

    public static final int tribeCount(String param) {
        String i = "0";
        if (StringUtils.isNotBlank(param) && param.length() > 1) {
            i = param.substring(1, param.length());
        }

        return StringUtils.isNotBlank(i) ? Integer.valueOf(i) : 0;
    }

    public static String endsWith(String s) {
        String value = "";
        //判断最后一个字符是否为“段”
        if (s.endsWith(",")) {
            value = s.substring(0, s.length() - 1);
        }
        return value;

    }

    /**
     * 将分为单位的转换为元 （除100）
     *
     * @param amount
     * @return
     * @throws Exception
     */
    public static String feeToYuan(String amount) {

        /**金额为分的格式 */
        if (!amount.matches("\\-?[0-9]+")) {
//            log.error(" FuYouFile 金额格式有误");
            return "0";
        }

        BigDecimal bigDecimal = BigDecimal.valueOf(Long.valueOf(amount)).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 不足两位小数补0
        DecimalFormat decimalFormat = new DecimalFormat("0.00#");
        String strVal = decimalFormat.format(bigDecimal);

        return bigDecimal.toString();
    }

    public static boolean isMailbox(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
//        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; //验证邮箱
        String check = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"; //验证邮箱
        if (StringUtils.isNotBlank(str)) {
            p = Pattern.compile(check);
            m = p.matcher(str);
            b = m.matches();
        }
        return b;
    }

    /*  <br data-filtered="filtered">　　　　　2019年1月16日已知
       中国电信号段
           133,149,153,173,174,177,180,181,189,199
       中国联通号段
           130,131,132,145,146,155,156,166,175,176,185,186
       中国移动号段
           134(0-8),135,136,137,138,139,147,148,150,151,152,157,158,159,165,178,182,183,184,187,188,198
       上网卡专属号段（用于上网和收发短信，不能打电话）
           如中国联通的是145
       虚拟运营商
           电信：1700,1701,1702
           移动：1703,1705,1706
           联通：1704,1707,1708,1709,171
       卫星通信： 1349 <br data-filtered="filtered">　　　　　未知号段：141、142、143、144、154
       */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
//        String s2="^[1](([3|5|8][\\d])|([4][4,5,6,7,8,9])|([6][2,5,6,7])|([7][^9])|([9][1,8,9]))[\\d]{8}$";// 验证手机号
        String s2 = "^((13[0-9])|(14[0,1,4,5,6,8,7,9])|(15([0-3]|[5-9]))|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[[0-3],[5-9]]))\\d{8}$";
        if (StringUtils.isNotBlank(str)) {
            p = Pattern.compile(s2);
            m = p.matcher(str);
            b = m.matches();
        }
        return b;
    }

    public static String getRate(int num1,int num2){
        //创建一个数值格式化对象
        java.text.NumberFormat numberformat = java.text.NumberFormat.getInstance();
        //设置精确到小数点后2位
        numberformat.setMaximumFractionDigits(2);
        String result1 = numberformat.format((float) num1 / (float) num2 * 100);
//        System.out.println("num1和num2的百分比是：result1="+result1+"%");
//        java.text.DecimalFormat df=new java.text.DecimalFormat("##.##%");//传入格式模板
//        String result2=df.format((float)num1/(float)num2);
//        System.out.println("num1和num2的百分比是：result2="+result2+"%");
        return result1;
    }

    /**
     * @Function: 生成验证码
     * @author:   zhenzhuobin
     */
    public static String getMsgCode(int n) {
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }
    public static String phoneReplace(String  phone) {

        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
    }


}

